<template>
  <div>
    <div style="margin-bottom: 16px;">
      <a-form-item label="网址">
          <a-input v-model="params.bookSourceUrl"></a-input>
      </a-form-item>
      <a-button type="primary" style="margin-right: 8px;" @click="$router.push('/source/add')">添加</a-button>
      <a-button type="primary" @click="visible = true">导入</a-button>
    </div>
    <a-table :dataSource="filterList" :columns="columns">
      <span slot="action" slot-scope="text, record">
        <a href="javascript:;" @click="$router.push(`/source/${record._id}`)">详情</a>
        <a-divider type="vertical" />
        <a href="javascript:;" @click="$router.push(`/source/edit/${record._id}`)">编辑</a>
       <a-divider type="vertical" />
        <a href="javascript:;" @click="remove(record)">删除</a>
        <a-divider type="vertical" />
        <a href="javascript:;" @click="$router.push({ path: '/', query: { sourceId: record._id }})">搜索</a>
      </span>
    </a-table>
    <a-modal :visible="visible" title="导入" @ok="handleImport" @cancel="visible = false">
      <a-form>
        <a-form-item label="书源代码">
          <a-textarea v-model="code" :row="10"></a-textarea>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { getSourceList, removeSource, batchAddSources } from '@/api'
export default {
  data () {
    return {
      list: [],
      visible: false,
      code: '',
      columns: [
        {
          dataIndex: '_id',
          title: 'id'
        },
        {
          dataIndex: 'bookSourceName',
          title: '站名'
        },
        {
          title: 'Action',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      params: {
        bookSourceUrl: ''
      }
    }
  },
  created () {
    this.getList()
  },
  computed: {
    filterList () {
      if (this.params.bookSourceUrl) {
        return this.list.filter(x => x.bookSourceUrl.includes(this.params.bookSourceUrl))
      }
      return this.list
    }
  },
  methods: {
    async handleImport () {
      if (!this.code) {
        this.$message.error('请输入代码')
        return
      }
      await batchAddSources({ url: this.code })
      this.visible = false
      this.getList()
      this.$message.success('导入成功')
    },
    getList () {
      return getSourceList().then(res => {
        this.list = res
      })
    },
    remove (record) {
      this.$confirm({
        title: '提示',
        content: '确认删除?',
        onOk: () => {
          return removeSource({ _id: record._id }).then(res => {
            return this.getList()
          })
        }
      })
    }
  }
}
</script>

<style>

</style>